<script setup lang="ts">
import {h} from 'vue';
import {Button, message, Modal as AntModal, Tag} from 'ant-design-vue';
import {Page} from '#/components/common-ui';
import {useDrawer, useModal, useVxeGrid} from '#/ui-kit';
import {useDictStore} from '#/stores';

import {findDictListPage, removeDictInfo} from '#/api/system/dict';

import DictChangeModal from './dict-change-modal.vue';
import DictItemDrawer from './item/index.vue';

const {getDictData} = useDictStore();

const [Grid, gridApi] = useVxeGrid({
  tableTitle: '字典列表',
  gridOptions: {
    columns: [
      {fixed: 'left', title: '#', type: 'seq', minWidth: 50},
      {field: 'name', title: '字典名称', minWidth: 120,},
      {slots: {default: 'code'}, title: '字典编码', minWidth: 120,},
      {
        slots: {
          default: ({row}) => {
            const data = getDictData('enable_status', true).find(item => item.value === row.enableStatus);
            return h(Tag, {color: data?.color || 'default'}, () => data?.label || '未知');
          }
        }, title: '启用状态', minWidth: 80,
      },
      {field: 'remark', title: '备注', minWidth: 180,},
      {field: 'createTime', title: '创建时间', formatter: 'formatDateTime', minWidth: 180,},
      {fixed: 'right', slots: {default: 'action'}, title: '操作', minWidth: 180},
    ],
    proxyConfig: {
      ajax: {
        query: async ({page}, formValues) => {
          return await getDictListPage({
            pageNumber: page.currentPage,
            pageSize: page.pageSize,
            ...formValues
          });
        },
      }
    },
    stripe: true,
    keepSource: true,
    height: 'auto',
    toolbarConfig: {
      custom: true,
      refresh: true,
      zoom: true,
    },
  },
  formOptions: {
    commonConfig: {
      componentProps: {
        allowClear: true,
      }
    },
    schema: [
      {
        label: '字典名称',
        fieldName: 'name',
        component: 'Input',
        componentProps: {
          placeholder: '请输入字典名称',
        },
      },
      {
        label: '字典编码',
        fieldName: 'code',
        component: 'Input',
        componentProps: {
          placeholder: '请输入字典编码',
        },
      },
      {
        label: '启用状态',
        fieldName: 'enableStatus',
        component: 'Select',
        componentProps: {
          options: getDictData('enable_status', true),
          placeholder: '请选择启用状态',
        },
      },
    ],
    showCollapseButton: true,
    collapsed: true,
  }
});

const [Modal, modalApi] = useModal({
  class: 'w-[750px]',
  connectedComponent: DictChangeModal,
});

const [Drawer, drawerApi] = useDrawer({
  title: '字典项列表',
  class: 'w-[980px]',
  connectedComponent: DictItemDrawer,
});

const getDictListPage = (params) => {
  return new Promise<{ items: any; total: number }>((resolve) => {
    findDictListPage(params).then(res => {
      resolve({
        items: res.records,
        total: res.totalRow,
      });
    }).catch(() => {
      resolve({
        items: [],
        total: 0,
      });
    })
  });
}

const handleCreateDict = () => {
  modalApi.setState({title: '新增字典'});
  modalApi.open();
}

const handleUpdateDict = (row) => {
  modalApi.setState({title: '更新字典'});
  modalApi.setData(row);
  modalApi.open();
}

const handleRemoveDict = (row) => {
  AntModal.confirm({
    title: '提示',
    content: '是否确认删除此字典，删除后相应的字典项也将删除！',
    centered: true,
    async onOk() {
      await removeDictInfo(row.id).then(() => {
        gridApi.reload();
        message.success('字典删除成功');
      });
    }
  });
}

const handleDictCodeClick = (row) => {
  drawerApi.setData(row);
  drawerApi.open();
}
</script>

<template>
  <Page auto-content-height>
    <Grid>
      <template #toolbar-tools>
        <Button type="primary" v-access:code="['sys:dict:create']" @click="handleCreateDict()">新增字典</Button>
      </template>
      <template #code="{row}">
        <Button type="link" size="small" @click="handleDictCodeClick(row)">{{ row.code }}</Button>
      </template>

      <template #action="{row}">
        <Button type="link" size="small" v-access:code="['sys:dict:update']" @click="handleUpdateDict(row)">编辑
        </Button>
        <Button type="link" size="small" v-access:code="['sys:dict:remove']" @click="handleRemoveDict(row)">删除
        </Button>
      </template>
    </Grid>

    <Modal @close="() => gridApi.reload()"/>

    <Drawer/>
  </Page>
</template>